import { defineStore } from 'pinia'
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import type {
  UserPreferences,
  SystemConfig,
  IntegrationConfig,
  NotificationChannel
} from '@/api/settings'
import {
  getUserPreferences,
  updateUserPreferences,
  getSystemConfig,
  updateSystemConfig,
  getIntegrationConfig,
  getNotificationChannels,
  updateNotificationChannels,
  resetUserSettings
} from '@/api/settings'

export const useSettingsStore = defineStore('settings', () => {
  // State
  const userPreferences = ref<UserPreferences>({
    theme: 'light',
    language: 'auto',
    timezone: 'UTC',
    dateFormat: 'YYYY-MM-DD',
    timeFormat: '24h',
    notifications: {
      email: true,
      browser: true,
      sound: false
    },
    dashboard: {
      layout: ['overview', 'alerts', 'tickets', 'performance'],
      defaultView: 'overview'
    }
  })

  const systemConfig = ref<SystemConfig>({
    siteName: 'DevOps SmartBot',
    siteUrl: 'http://localhost:3000',
    adminEmail: 'admin@devops.com',
    alertRetentionDays: 90,
    ticketRetentionDays: 365,
    enableAIAnalysis: true,
    enableAutoCreateTicket: true,
    slaEnabled: true,
    slaPolicies: {
      critical: 4,
      high: 8,
      medium: 24,
      low: 48
    },
    maintenanceMode: false,
    maintenanceMessage: ''
  })

  const integrationConfig = ref<IntegrationConfig>({})
  const notificationChannels = ref<NotificationChannel[]>([])
  const loading = ref(false)

  // Actions
  const fetchUserPreferences = async () => {
    try {
      loading.value = true
      const response = await getUserPreferences()
      if (response.data) {
        userPreferences.value = response.data
      }
      return userPreferences.value
    } catch (error) {
      console.error('Failed to fetch user preferences:', error)
      message.error('Failed to load user preferences')
      throw error
    } finally {
      loading.value = false
    }
  }

  const saveUserPreferences = async (preferences: Partial<UserPreferences>) => {
    try {
      loading.value = true
      const response = await updateUserPreferences(preferences)
      if (response.data) {
        userPreferences.value = { ...userPreferences.value, ...preferences }
        message.success('User preferences saved successfully')
      }
      return response
    } catch (error) {
      console.error('Failed to save user preferences:', error)
      message.error('Failed to save user preferences')
      throw error
    } finally {
      loading.value = false
    }
  }

  const fetchSystemConfig = async () => {
    try {
      loading.value = true
      const response = await getSystemConfig()
      if (response.data) {
        systemConfig.value = response.data
      }
      return systemConfig.value
    } catch (error) {
      console.error('Failed to fetch system config:', error)
      message.error('Failed to load system configuration')
      throw error
    } finally {
      loading.value = false
    }
  }

  const saveSystemConfig = async (config: Partial<SystemConfig>) => {
    try {
      loading.value = true
      const response = await updateSystemConfig(config)
      if (response.data) {
        systemConfig.value = { ...systemConfig.value, ...config }
        message.success('System configuration saved successfully')
      }
      return response
    } catch (error) {
      console.error('Failed to save system config:', error)
      message.error('Failed to save system configuration')
      throw error
    } finally {
      loading.value = false
    }
  }

  const fetchIntegrationConfig = async () => {
    try {
      loading.value = true
      const response = await getIntegrationConfig()
      if (response.data) {
        integrationConfig.value = response.data
      }
      return integrationConfig.value
    } catch (error) {
      console.error('Failed to fetch integration config:', error)
      message.error('Failed to load integration configuration')
      throw error
    } finally {
      loading.value = false
    }
  }

  const fetchNotificationChannels = async () => {
    try {
      loading.value = true
      const response = await getNotificationChannels()
      if (response.data) {
        notificationChannels.value = response.data
      }
      return notificationChannels.value
    } catch (error) {
      console.error('Failed to fetch notification channels:', error)
      message.error('Failed to load notification channels')
      throw error
    } finally {
      loading.value = false
    }
  }

  const saveNotificationChannels = async (channels: NotificationChannel[]) => {
    try {
      loading.value = true
      const response = await updateNotificationChannels(channels)
      if (response.data) {
        notificationChannels.value = channels
        message.success('Notification channels saved successfully')
      }
      return response
    } catch (error) {
      console.error('Failed to save notification channels:', error)
      message.error('Failed to save notification channels')
      throw error
    } finally {
      loading.value = false
    }
  }

  const resetSettings = async () => {
    try {
      loading.value = true
      await resetUserSettings()
      await fetchUserPreferences()
      message.success('Settings reset to defaults successfully')
    } catch (error) {
      console.error('Failed to reset settings:', error)
      message.error('Failed to reset settings')
      throw error
    } finally {
      loading.value = false
    }
  }

  const updateTheme = async (theme: 'light' | 'dark' | 'auto') => {
    await saveUserPreferences({ ...userPreferences.value, theme })

    // Apply theme to document
    if (theme === 'dark') {
      document.documentElement.classList.add('dark')
    } else if (theme === 'light') {
      document.documentElement.classList.remove('dark')
    } else {
      // Auto mode - check system preference
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      if (prefersDark) {
        document.documentElement.classList.add('dark')
      } else {
        document.documentElement.classList.remove('dark')
      }
    }
  }

  const updateLanguage = async (language: 'en' | 'zh' | 'auto') => {
    await saveUserPreferences({ ...userPreferences.value, language })
    // TODO: Implement i18n language switching
  }

  // Initialize - fetch all settings
  const initialize = async () => {
    try {
      await Promise.all([
        fetchUserPreferences(),
        fetchSystemConfig(),
        fetchIntegrationConfig(),
        fetchNotificationChannels()
      ])
    } catch (error) {
      console.error('Failed to initialize settings:', error)
    }
  }

  return {
    // State
    userPreferences,
    systemConfig,
    integrationConfig,
    notificationChannels,
    loading,

    // Actions
    fetchUserPreferences,
    saveUserPreferences,
    fetchSystemConfig,
    saveSystemConfig,
    fetchIntegrationConfig,
    fetchNotificationChannels,
    saveNotificationChannels,
    resetSettings,
    updateTheme,
    updateLanguage,
    initialize
  }
})
